import { ref } from 'vue';
import { defineStore } from 'pinia';
import { $fetch } from '@/mobile/utils/fetch';
import { HEADER_KEY_COMMUNITY, HEADER_KEY_LANGUAGE, HEADER_KEY_TOKEN } from '@/common/utils/constants';

// 全局 APP 相关信息放在这个 store 中

export interface SiteConfig {
  name: string,
  description: string,
  logo: string,
  headLogo: string,
  address: string,
  userNumber: number,
  communityOrgNumber: number,
  communityWarehouseNumber: number,
  medium: Record<string, any>[],
  qrcode: string,
  seo: {
    title: string,
    description: string,
    keywords: string,
  },
  stats: {
    baidu: '',
  },
}

export const useAppStore = defineStore('app', () => {
  const config = ref<SiteConfig>({
    name: '',
    description: '',
    logo: '',
    headLogo: '',
    address: '',
    userNumber: 0,
    communityOrgNumber: 0,
    communityWarehouseNumber: 0,
    medium: [],
    qrcode: '',
    seo: {
      title: '',
      description: '',
      keywords: '',
    },
    stats: {
      baidu: '',
    },
  });
  const uiStore = ref({
    tabsFixed: false,
  });
  const user = ref<Record<string, any>>({});

  // 从服务器获取全站配置等信息
  async function fetchConfigForServer({ language, community, token }: Record<string, any>) {
    const { isSuccess, data } = await $fetch('/community/getCommunityInfo', {
      headers: {
        [HEADER_KEY_COMMUNITY]: community,
        [HEADER_KEY_TOKEN]: token,
        [HEADER_KEY_LANGUAGE]: language,
      },
    });

    if (isSuccess) {
      config.value = {
        name: data.communityName,
        description: data.commIllustrate,
        logo: data.communityLogo,
        headLogo: data.communityHeadPic,
        address: data.commAddress,
        userNumber: data.communityUserNumber,
        communityOrgNumber: data.communityOrgNumber,
        communityWarehouseNumber: data.communityWarehouseNumber,
        medium: data.atomgitPopCommunityMediumVOList,
        qrcode: data.communityPic,
        seo: {
          title: data.commTitle,
          description: data.commDesc,
          keywords: data.commKeywords,
        },
        stats: {
          baidu: data.statisticConfig?.baidu?.id ?? '',
        },
      };
    }

    return isSuccess;
  }

  // 从服务器获取用户信息
  async function fetchUserForServer({ language, community, token }: Record<string, any>) {
    const { isSuccess, data } = await $fetch('/user/userInfo', {
      headers: {
        [HEADER_KEY_COMMUNITY]: community,
        [HEADER_KEY_TOKEN]: token,
        [HEADER_KEY_LANGUAGE]: language,
      },
    });

    if (isSuccess) {
      user.value = {
        id: data.id,
        photo: data.photo,
        email: data.email,
        username: data.username,
        nickname: data.nickname,
        isAdmin: data.allowLoginAdmin,
      };
    }

    return isSuccess;
  }

  return {
    fetchConfigForServer,
    fetchUserForServer,
    config,
    user,
    uiStore,
  };
});
